//
//  RecordsViewController.m
//  MagicCardDemo
//
//  Created by 向恒 on 15/7/5.
//  Copyright (c) 2015年 向恒. All rights reserved.
//

#import "RecordsViewController.h"//这个类改名叫RecordsListViewController比较好。
#import "AppDelegate.h"
#import "RecordDetailViewController.h"
#import "PracticeViewController.h"
#import "CardQueue.h"
//#import "CardData.h"
#import "CardSerialize.h"//20160123，要用类别就不要import CardData？

@interface RecordsViewController ()

@end

@implementation RecordsViewController
AppDelegate* appDelegate2;

//NSArray* recordFileList;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"记录";
    
    self.table.dataSource = self;
    self.table.delegate = self;
    
    UIBarButtonItem* btnEdit = [[UIBarButtonItem alloc]initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(btnAddRecord)];
    self.navigationItem.rightBarButtonItem = btnEdit;
    
    UIBarButtonItem* btnAdd = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(btnEditRecord)];
    self.navigationItem.leftBarButtonItem = btnAdd;
    //self.navigationController.navigationBar.barTintColor=[UIColor greenColor];
    self.table.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    appDelegate2 = [UIApplication sharedApplication].delegate;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

//进入编辑模式，确定编辑提交操作时，执行的代理方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle == UITableViewCellEditingStyleDelete)
    {
        [self.table beginUpdates];
 
        //删除文件 开始  ，这里的文件创建和删除应该使用同一个
        NSArray* doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString* docPath = [doc objectAtIndex:0];
        
        NSMutableArray * arr = [NSMutableArray arrayWithArray:appDelegate2.recordFileList];
        NSString* filePath = [docPath stringByAppendingPathComponent:[arr objectAtIndex:indexPath.row]];
        
        NSFileManager* fileMgr = [NSFileManager defaultManager];
        NSError* error;
        if([fileMgr removeItemAtPath:filePath error:&error] != YES)
        {
            NSLog(@"Unable to delete file:%@",filePath);
        }
        //删除文件结束
        
        [arr removeObjectAtIndex:indexPath.row];
        
        appDelegate2.recordFileList = arr;
        [self.table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        [self.table  endUpdates];
        
    }
    
//    [self.table reloadData];
//    if(editingStyle == UITableViewCellEditingStyleInsert)
//    {
//        [self.table beginUpdates];
//        
//        [self.table insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
//        [self.table endUpdates];
//    }
}

-(void)btnEditRecord
{
    //    DisplayRecordsViewController* drvc = [[DisplayRecordsViewController alloc] initWithNibName:@"DisplayRecordsViewController" bundle:nil];
    //    //svc.view.backgroundColor = [UIColor redColor];
    //    drvc.title = @"显示排版";
    //    self.hidesBottomBarWhenPushed  = YES;
    //    [self.navigationController pushViewController:drvc animated:YES];
    
    if(self.table.editing  == YES)
    {
        [self.table setEditing:NO animated:YES];
    }
    else
    {
        [self.table setEditing:YES animated:YES];
    }
    
    NSLog(@"btnEditRecord called.");
}

-(void)btnAddRecord
{
//    DisplayRecordsViewController* drvc = [[DisplayRecordsViewController alloc] initWithNibName:@"DisplayRecordsViewController" bundle:nil];
//    //svc.view.backgroundColor = [UIColor redColor];
//    drvc.title = @"显示排版";
//    self.hidesBottomBarWhenPushed  = YES;
//    [self.navigationController pushViewController:drvc animated:YES];
    
    //PracticeViewController* pv = [[PracticeViewController alloc]init];
    PracticeViewController* pv = [self.storyboard instantiateViewControllerWithIdentifier:@"idAddRecord"];
    pv.title = @"第一次练习";
    self.hidesBottomBarWhenPushed  = YES;
    [self.navigationController pushViewController:pv animated:YES];
    
    NSLog(@"btnAddRecord called.");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//这个是表格初始化的代码？
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellId = @"cellId2";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    }
    
    NSUInteger rowNo = indexPath.row;
    NSString* filename =[appDelegate2.recordFileList objectAtIndex:rowNo];
    NSArray* tmpArr1 = [filename componentsSeparatedByString:@"."];
    NSArray* tmpArr2 = [[tmpArr1 objectAtIndex:0] componentsSeparatedByString:@"--"];
    if(tmpArr2.count == 2)
    {
        NSMutableString* date = [NSMutableString stringWithString:[tmpArr2 objectAtIndex:0]];
        [date insertString:@"/" atIndex:6];
        [date insertString:@"/" atIndex:4];

        //从文件中读取时间和数字个数。
        //add 20160123  添加衡量成绩的数值
        CardQueue* queue = [CardData ReadDataFromFile:filename];
        float countPerMin = (float)queue.arrCards.count/queue.nCostTime;
        countPerMin = countPerMin*60;
        NSString* strRate = [NSString stringWithFormat:@"%.1f 个/分钟。共%ld个，耗时：%02d'%02d''",countPerMin,queue.arrCards.count,queue.nCostTime/60,queue.nCostTime%60];
        cell.textLabel.text = strRate;//这里现在要填：个数/分钟
        cell.layer.cornerRadius  = 12;
        cell.layer.masksToBounds = YES;
        //这一行的代码就有问题，这里应该是从文件中读取的
        //cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",appDelegate2.cardData.TrainQueue.date];
        NSMutableString* time = [NSMutableString stringWithString:[tmpArr2 objectAtIndex:1]];
        [time insertString:@":" atIndex:4];
        [time insertString:@":" atIndex:2];
        [date appendString:@" "];
        [date appendString:time];
        cell.detailTextLabel.text = date;
    }
    else{
        cell.textLabel.text = @"未知";
        cell.layer.cornerRadius  = 12;
        cell.layer.masksToBounds = YES;
        //这一行的代码就有问题，这里应该是从文件中读取的
        //cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",appDelegate2.cardData.TrainQueue.date];
        cell.detailTextLabel.text = @"";
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //这个地方应该是写入的记录的个数
    return appDelegate2.recordFileList.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    //跳转到指定的页面，根据segue标志来查找这个页面
    RecordDetailViewController * view  = [self.storyboard instantiateViewControllerWithIdentifier:@"idRecordDetail"];
    
//    //因为在对象创建之前赋值所以没有用？没有执行viewDidLoad之前。
//    //view.editingIndexPath = indexPath;
//    //view.selectRowNo = indexPath.row;
//    //int row = indexPath.row;
//    [self performSegueWithIdentifier:@"RecordDetail" sender:nil];
    
    
    //RecordDetailViewController * view = [[RecordDetailViewController alloc]init];
    NSInteger row = indexPath.row;
    [RecordDetailViewController setSelectRowNo:row];
    view.title = @"详细记录";
    NSLog(@"tableview navigationcontroller :%@",self.navigationController);
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:view animated:YES];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    self.hidesBottomBarWhenPushed = NO;
}

//这个view每出现一次就遍历一次，现在没什么问题，后面如果文件多了，应该会很有问题。
-(void)viewWillAppear:(BOOL)animated
{
    NSArray* doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* docPath = [doc objectAtIndex:0];
    //在这个地方读取文件
    NSArray* tmpList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:docPath error:nil];
    appDelegate2.recordFileList = [tmpList pathsMatchingExtensions:@[@"archive"]];

    
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|
    NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        NSComparisonResult* rst = [obj1 compare:obj2 options:comparisonOptions range:range];
//        if(rst == NSOrderedDescending)
//            return NSOrderedAscending;
//        if(rst == NSOrderedAscending)
//            return NSOrderedDescending;
//        return NSOrderedSame;
        return (NSComparisonResult)-1*(int)rst;
    };
//    NSArray *resultArray2 = [appDelegate2.recordFileList sortedArrayUsingComparator:sort];

    appDelegate2.recordFileList = [appDelegate2.recordFileList sortedArrayUsingComparator:sort];
    NSLog(@"字符串数组排序结果%@",appDelegate2.recordFileList);
    [self.table reloadData];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
